﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace RMSoftware.Models
{
    public class DataManager
    {
        private RMDatabaseEntities _db;

        public DataManager()
        {
            _db = new RMDatabaseEntities();
        }

        public IQueryable<Risk> RiskFactors
        {
            get
            {
                return _db.Risks;
            }
        }

        public IQueryable<Person> Persons
        {
            get
            {
                return _db.Persons;
            }
        }

        public IQueryable<Project> GetProjects()
        {
            return _db.Projects;
        }

        public Project GetProject(Guid id)
        {
            return _db.Projects.SingleOrDefault(proj => proj.ProjectId == id);
        }

        public void SaveProject(Project obj)
        {
            Project old = GetProject(obj.ProjectId);

            if (old == null)
            {
                _db.Projects.AddObject(obj);
            }
            else
            {
                old.Title = obj.Title;
            }

            _db.SaveChanges();
        }

        public Risk GetRiskFactor(Guid id)
        {
            return _db.Risks.SingleOrDefault(fact => fact.RiskId == id);
        }

        public void AddRiskFactor(Risk obj)
        {
            _db.Risks.AddObject(obj);
            _db.SaveChanges();
        }

        public void DeleteRiskFactor(Guid id)
        {
            _db.Risks.DeleteObject(GetRiskFactor(id));
            _db.SaveChanges();
        }

        public Person GetPerson(Guid id)
        {
            return _db.Persons.SingleOrDefault(pers => pers.PersonId == id);
        }

        public void AddPerson(Person obj)
        {
            _db.Persons.AddObject(obj);
            _db.SaveChanges();
        }

        public void DeletePerson(Guid id)
        {
            _db.Persons.DeleteObject(GetPerson(id));
            _db.SaveChanges();
        }

        public void AddRisk(ProjectRisk obj)
        {
            _db.ProjectRisks.AddObject(obj);
            _db.SaveChanges();
        }

        public ProjectRisk GetRisk(Guid id)
        {
            return _db.ProjectRisks.SingleOrDefault(pr => pr.ProjectRiskId == id);
        }

        public void DeleteRisk(Guid id)
        {
            _db.ProjectRisks.DeleteObject(GetRisk(id));
            _db.SaveChanges();
        }

        public void DeleteRisk(ProjectRisk obj)
        {
            _db.ProjectRisks.DeleteObject(obj);
            _db.SaveChanges();
        }
    }
}